package com.yanqu.road.server.manger.activity.auto.reward;

import com.yanqu.road.entity.DataStatus;
import com.yanqu.road.entity.activity.ActivityConditionInfo;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.UserActivityConditionData;
import com.yanqu.road.entity.activity.auto.reward.UserEveryDayChargeReward;
import com.yanqu.road.entity.enums.activity.eActivityChargeType;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eMailType;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.logic.bussiness.player.activity.auto.reward.RechargeActivityAutoRewardBusiness;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.logic.mail.MailManager;
import com.yanqu.road.server.manger.MultipleLanguageMgr;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author wpj
 * @Date 2020/8/27
 */
public class ActivityAutoRewardMgr extends TempMgr {
    // activityId timeMark conditionId userId
    private static Map<Integer, Map<Integer, Map<Integer, Map<Long, UserEveryDayChargeReward>>>> autoRewardRecordMap;

    public static Map<Integer, Map<Integer, Map<Integer, Map<Long, UserEveryDayChargeReward>>>> getAutoRewardRecordMap() {
        return autoRewardRecordMap;
    }

    /**
     * 设置自动发邮件的值
     *
     * @param userActivityConditionData
     */
    public static void setValue(UserActivityConditionData userActivityConditionData, long time) {
        try {
            if (userActivityConditionData.getValue().compareTo(BigInteger.ZERO) <= 0) {
                // 大于等于0的才写入
                return;
            }
            // 判断是否是自动发邮件的活动
            int activityId = userActivityConditionData.getActivityId();
            ActivityInfo activityInfo = NormalActivityMgr.getAllActivityInfoMap().get(activityId);
            if (activityInfo == null || !ActivityMgr.isNeedAutoRewardReChageActivity(activityInfo)) {
                return;
            }

            long userId = userActivityConditionData.getUserId();
            int timeMark = 0;
            int conditionId = userActivityConditionData.getConditionId();

            // 如果是每日充值 则timeMark为每天的标记
            if (ActivityMgr.isEveryDayReChargeActivity(activityInfo)) {
                if (time == 0) {
                    // 若没初始化则使用当前时间
                    time = System.currentTimeMillis() / 1000;
                }
                timeMark = Integer.valueOf(DateHelper.getPyyyyMMddDateString(time));
            }

            synchronized (autoRewardRecordMap) {
                if (!autoRewardRecordMap.containsKey(activityId)) {
                    autoRewardRecordMap.put(activityId, new ConcurrentHashMap<>());
                }
                if (!autoRewardRecordMap.get(activityId).containsKey(timeMark)) {
                    autoRewardRecordMap.get(activityId).put(timeMark, new ConcurrentHashMap<>());
                }
                if (!autoRewardRecordMap.get(activityId).get(timeMark).containsKey(conditionId)) {
                    autoRewardRecordMap.get(activityId).get(timeMark).put(conditionId, new ConcurrentHashMap<>());
                }
                UserEveryDayChargeReward userEveryDayChargeReward = autoRewardRecordMap.get(activityId).get(timeMark).get(conditionId).get(userId);
                if (userEveryDayChargeReward == null) {
                    UserEveryDayChargeReward reward = new UserEveryDayChargeReward();
                    reward.setActivityId(activityId);
                    reward.setUserId(userId);
                    reward.setConditionId(conditionId);
                    reward.setTimeMark(timeMark);
                    reward.setValue(userActivityConditionData.getValue());
                    reward.setReward(userActivityConditionData.isGetReward());
                    reward.setInsertOption();
                    autoRewardRecordMap.get(activityId).get(timeMark).get(conditionId).put(userId, reward);
                } else {
                    userEveryDayChargeReward.setValue(userActivityConditionData.getValue());
                    if(!userEveryDayChargeReward.isReward()) {//领完奖了就不要再设置回去
                        userEveryDayChargeReward.setReward(userActivityConditionData.isGetReward());
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {

        }
    }

    /**
     * 自动发送邮件
     */
    public static void autoSendReward() {
        List<UserEveryDayChargeReward> userEveryDayChargeRewardList = new ArrayList<>();
        synchronized (autoRewardRecordMap) {
            // 先把需要发奖的挑出来
            List<Integer> activityIdList = new ArrayList<>(autoRewardRecordMap.keySet());
            for (int activityId : activityIdList) {
                ActivityInfo activityInfo = NormalActivityMgr.getAllActivityInfoMap().get(activityId);
                if (activityInfo == null) {
                    getLogger().error("activity is null, activityId : {}",  activityId);
                    continue;
                }

                List<ActivityConditionInfo> conditionInfoList = new ArrayList<>();
                // 筛选 TODO 如果有多个的话要做一下处理//
                List<ActivityConditionInfo> tempConditionList = NormalActivityMgr.getActivityConditionInfoList(activityId);
                if(null != tempConditionList) {
                    for (ActivityConditionInfo activityConditionInfo : tempConditionList) {
                        if (activityConditionInfo.getType() == eGamePlayerEventType.Recharge.getValue() || activityConditionInfo.getType() == eGamePlayerEventType.RechargeDays.getValue()) {
                            conditionInfoList.add(activityConditionInfo);
                        }
                    }
                }
                if (conditionInfoList.size() == 0) {
                    getLogger().error("condition size is zero, activityId : {}",  activityId);
                    continue;
                }

                if (ActivityMgr.isEveryDayReChargeActivity(activityInfo)) {
                    int todayTimeMark = Integer.valueOf(DateHelper.getPyyyyMMddDateString(System.currentTimeMillis() / 1000));
                    // 每日充值 需要把所有的给掏出来 需要判断timeMark
                    for (int timeMark : autoRewardRecordMap.get(activityId).keySet()) {
                        if (todayTimeMark > timeMark) {
                            // 自动发奖时间已到 判断是否领奖并且添加到发奖列表
                            for (int conditionId : autoRewardRecordMap.get(activityId).get(timeMark).keySet()) {
                                int conditionIndex = getConditionIndexFromList(conditionInfoList, conditionId);
                                ActivityConditionInfo activityConditionInfo = NormalActivityMgr.getActivityConditionInfo(activityId, conditionId);
                                if (activityConditionInfo == null) {
                                    getLogger().error("conditionInfo is null, activityId : {}, conditionId : {}",  activityId, conditionId);
                                    continue;
                                }
                                for (UserEveryDayChargeReward userEveryDayChargeReward : autoRewardRecordMap.get(activityId).get(timeMark).get(conditionId).values()) {
                                    if (!userEveryDayChargeReward.isReward() && userEveryDayChargeReward.getValue().compareTo(activityConditionInfo.getParamList().get(3)) >= 0 ) {
                                        userEveryDayChargeReward.setRewardStr(activityConditionInfo.getRewardStr());

                                        UserInfo userInfo = UserMgr.getUserInfo(userEveryDayChargeReward.getUserId());
                                        if (userInfo == null) {
                                            getLogger().error("userInfo is null, userId : {}", userEveryDayChargeReward.getUserId());
                                            continue;
                                        }
                                        String title = MultipleLanguageMgr.getContent(MailManager.EVERY_DAY_RECHARGE_REWARD_SEND_TITLE, userInfo.getLanguage());
                                        String content = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.EVERY_DAY_RECHARGE_REWARD_SEND_CONTENT, userInfo.getLanguage()), conditionIndex);
                                        userEveryDayChargeReward.setTitle(title);
                                        userEveryDayChargeReward.setContent(content);
                                        userEveryDayChargeRewardList.add(userEveryDayChargeReward);
                                    }
                                }
                            }
                        }
                    }
                } else if (ActivityMgr.isDaysReChargeActivity(activityInfo)) {
                    // 累计充值 累天充值活动结束的挑出来 不需要判断timeMark 活动过期
                    if (System.currentTimeMillis() >= activityInfo.getEndShowTime() * 1000) {
                        // 活动过期
                        for (Map<Integer, Map<Long, UserEveryDayChargeReward>> conditionMap : autoRewardRecordMap.get(activityId).values()) {
                            for (int conditionId : conditionMap.keySet()) {

                                int conditionIndex = getConditionIndexFromList(conditionInfoList, conditionId);
                                ActivityConditionInfo activityConditionInfo = NormalActivityMgr.getActivityConditionInfo(activityId, conditionId);
                                if (activityConditionInfo == null) {
                                    getLogger().error("conditionInfo is null, activityId : {}, conditionId : {}",  activityId, conditionId);
                                    continue;
                                }

                                for (UserEveryDayChargeReward userEveryDayChargeReward : conditionMap.get(conditionId).values()) {
                                    if (!userEveryDayChargeReward.isReward() && userEveryDayChargeReward.getValue().compareTo(activityConditionInfo.getParamList().get(3)) >= 0 ) {

                                        UserInfo userInfo = UserMgr.getUserInfo(userEveryDayChargeReward.getUserId());
                                        if (userInfo == null) {
                                            getLogger().error("userInfo is null, userId : {}", userEveryDayChargeReward.getUserId());
                                            continue;
                                        }
                                        String title = "";
                                        String content = "";

                                        if (ActivityMgr.isMyActivityType(activityInfo, eActivityType.RechargeActivity, eActivityChargeType.AllCharge)) {
                                            title = MultipleLanguageMgr.getContent(MailManager.All_RECHARGE_REWARD_SEND_TITLE, userInfo.getLanguage());
                                            content = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.All_RECHARGE_REWARD_SEND_CONTENT, userInfo.getLanguage()), conditionIndex);
                                        } else if (ActivityMgr.isMyActivityType(activityInfo, eActivityType.RechargeActivity, eActivityChargeType.DaysCharge)) {
                                            title = MultipleLanguageMgr.getContent(MailManager.DAYS_RECHARGE_REWARD_SEND_TITLE, userInfo.getLanguage());
                                            content = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.DAYS_RECHARGE_REWARD_SEND_CONTENT, userInfo.getLanguage()), conditionIndex);
                                        } else if (ActivityMgr.isMyActivityType(activityInfo, eActivityType.RechargeActivity, eActivityChargeType.CanReissueDaysCharge)) {
                                            title = MultipleLanguageMgr.getContent(MailManager.DAYS_RECHARGE_REWARD_SEND_TITLE, userInfo.getLanguage());
                                            content = StringUtils.format(MultipleLanguageMgr.getContent(MailManager.DAYS_RECHARGE_REWARD_SEND_CONTENT, userInfo.getLanguage()), conditionIndex);
                                        }

                                        userEveryDayChargeReward.setTitle(title);
                                        userEveryDayChargeReward.setContent(content);
                                        userEveryDayChargeReward.setRewardStr(activityConditionInfo.getRewardStr());
                                        userEveryDayChargeRewardList.add(userEveryDayChargeReward);
                                    }
                                }
                            }
                        }
                    }

                }
            }
        }

        for (UserEveryDayChargeReward userEveryDayChargeReward : userEveryDayChargeRewardList) {
            String serverListStr = String.valueOf(GameServer.getInstance().getServerId());
            int activityId = 0;
            ActivityInfo activityInfo = NormalActivityMgr.getExistCrossBanquetRankActivity();
            if (activityInfo != null) {
                serverListStr = activityInfo.getServerListStr();
                activityId = activityInfo.getActivityId();
            }
            MailManager.sendMail(userEveryDayChargeReward.getUserId(), eMailType.SYSTEM.getValue(), userEveryDayChargeReward.getRewardStr(), userEveryDayChargeReward.getContent(), userEveryDayChargeReward.getTitle(), activityId, serverListStr);
            userEveryDayChargeReward.setReward(true);
        }

        // 把所有活动过期超过5天的移除内存
        synchronized (autoRewardRecordMap) {
            List<Integer> activityIdList = new ArrayList<>(autoRewardRecordMap.keySet());
            for (int activityId : activityIdList) {
                ActivityInfo activityInfo = NormalActivityMgr.getAllActivityInfoMap().get(activityId);
                if (activityInfo == null) {
                    getLogger().info("activity is null, activityId : {}",  activityId);
                    continue;
                }
                if (System.currentTimeMillis() >= activityInfo.getEndShowTime() * 1000 + 5 * 24 * 3600 * 1000) {
                    autoRewardRecordMap.remove(activityId);
                    getLogger().info("remove expired activity. activityId : {}", activityId);
                }
            }
        }
    }

    /**
     * 获取conditionId位于第几档
     * @param conditionInfoList
     * @param conditionId
     * @return
     */
    public static int getConditionIndexFromList(List<ActivityConditionInfo> conditionInfoList, int conditionId) {
        int i = 0;
        for (ActivityConditionInfo activityConditionInfo : conditionInfoList) {
            i++;
            if (activityConditionInfo.getConditionId() == conditionId) {
                return i;
            }
        }
        return i;
    }

    @Override
    public boolean reloadData() {
        autoRewardRecordMap = RechargeActivityAutoRewardBusiness.getUserEveryDayChargeReward(NormalActivityMgr.getExpiredActivityBiggerThanFiveDayList());
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    public boolean save() {
        List<UserEveryDayChargeReward> userEveryDayChargeRewardList = new ArrayList<>();
        synchronized (autoRewardRecordMap) {
            for (Map<Integer, Map<Integer, Map<Long, UserEveryDayChargeReward>>> timeMarkMap : autoRewardRecordMap.values()) {
                for (Map<Integer, Map<Long, UserEveryDayChargeReward>> conditionMap : timeMarkMap.values()) {
                    for (Map<Long, UserEveryDayChargeReward> userIdMap : conditionMap.values()) {
                        for (UserEveryDayChargeReward userEveryDayChargeReward : userIdMap.values()) {
                            if (userEveryDayChargeReward.getOp() != DataStatus.None) {
                                userEveryDayChargeRewardList.add(userEveryDayChargeReward);
                            }
                        }
                    }
                }
            }
        }

        for (UserEveryDayChargeReward userEveryDayChargeReward : userEveryDayChargeRewardList) {
            if (userEveryDayChargeReward.isInsertOption()) {
                RechargeActivityAutoRewardBusiness.addUserEveryDayChargeReward(userEveryDayChargeReward);
            } else if (userEveryDayChargeReward.isUpdateOption()) {
                RechargeActivityAutoRewardBusiness.updateUserEveryDayChargeReward(userEveryDayChargeReward);
            }
        }
        return true;
    }
}
